package com.example.demo.util;


import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangfc
 * @date 2021/8/29 17:20
 */
public class WordGeneratorUtil {
    private static Configuration configuration = null;

    private static Map<String, Template> allTemplates = null;

    private static final String TEMPLATE_URL = "/templates";

    /**
     * 模板常量配置
     */
    public static final class FreemarkerTempate {

        //自己文件的名称
        public static final String Test = "test_TemplateFinal";

        public static final String test_execl = "MYTEST_execl";

        public static final String REPORT = "report";

        public static final String REC_RECOMMEND = "recRecommend";
    }

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(WordGeneratorUtil.class, TEMPLATE_URL);
        allTemplates = new HashMap<>(4);

        try {
            allTemplates.put(FreemarkerTempate.Test, configuration.getTemplate(FreemarkerTempate.Test + ".ftl"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    private WordGeneratorUtil() {
        throw new AssertionError();
    }


    public static File createDoc(String freemarkerTemplate, String wordName, Map<String, Object> dataMap) {

        try {
            File file = new File(wordName);

            Template template = allTemplates.get(freemarkerTemplate);

            Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);

            template.process(dataMap, writer);

            writer.close();

            return file;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成word文档失败");
        }
    }
}
